/* eslint no-underscore-dangle: 0 */
import React, { Component } from 'react';
import { Button, Table, Pagination, Icon, Switch,Feedback } from '@icedesign/base';
import IceContainer from '@icedesign/container';
import {hashHistory} from 'react-router';
import DataBinder from '@icedesign/data-binder';
import IceLabel from '@icedesign/label';
import axios from 'axios';
import Config from '../../../../utils/Config'
import EditDialog from '../EditDialog'
import ConfirmDeleteDialog from '../../../Dialog/components/ConfirmDeleteDialog'
import {GET,POST,PUT} from '../../../../utils/public'

@DataBinder({
  tableData: {
    url: '/account/api/users',
    params: {
      page: 1,
      pageSize:10,
    },
    responseFormatter: (responseHandler, res, originResponse) => {
      // 做一些数据转换
      if(res.msg=="请登录!" && res.code==401){
        Feedback.toast.error(res.msg)
        setTimeout(()=>{
          hashHistory.push('/login');
        },1000)
        return;
        
      }else if(res.code !==200){
        Feedback.toast.error(res.msg);
        return;
      }
      const newRes = {
        status: res.code == 200 ? 'SUCCESS' : 'ERROR',
        message: res.msg,
        data:(res.code==200)?(res.data):{},
        page:(res.code==200)?(res.data.page):1,
      };
      
      
      // 回传给处理函数
      // 不做回传处理会导致数据更新逻辑中断
      responseHandler(newRes, originResponse);
    },
    defaultBindingData: {
      page:1,
      pageSize:10,
    },
  }
})
export default class UserInfoTable extends Component {
  static displayName = 'UserInfoTable';

  static propTypes = {};

  static defaultProps = {};

  constructor(props) {
    super(props);
    this.state = {
      checked:[],
      current:1,//当前页,默认值为1
    };
    this.handleChildChange=this.handleChildChange.bind(this);//监听子组件变化
  }

  handleChildChange(status){ //处理子函数传回来的status,status为true，重新请求用户列表
    if(status){
      let page = this.state.current;
      //翻页
      this.fetchData({
        page
      });
    }
  }

  componentDidMount() {
    this.fetchData({
      page: 1
    });
   
  }

  changePage = (currentPage) => {
    this.setState({current:currentPage})
    //翻页
    this.fetchData({
      page: currentPage,
    });
  };

  fetchData = ({ page }) => {
    this.props.updateBindingData('tableData', {
      params: {
        page
      },
    },(res)=>{
      if(res.code== 200 && res.success){
        let rows = res.data.rows;
        this.saveChecked(rows)
      }else if(res.code==401 && res.msg=='请登录!'){
        Feedback.toast.error(res.msg)
        setTimeout(()=>{
          hashHistory.push('/login');
        },3000)
        return;
      }else{
        Feedback.toast.error(res.msg)
      }
    });
  }

  saveChecked = (rows)=>{
    let arr = [];
    rows.forEach((item)=>{
      let checked= false;
      (item.status)?(arr.push(true)):(arr.push(false))
      //arr.push(checked)
    })
    this.setState({checked:arr})
  }

  onOpen=(record,type)=>{
    //record: 编辑时record为当前行的数据记录，添加时为空
    //type: edit编辑 add 添加
    this.refs.getOpenDialog.onOpen(record,type);
  }

  onDelete = (record)=>{
      //record: 为当前行的数据记录，添加时为空
      let id = record.id;     //当前记录id
      let url = '/api/users/' //url
      this.refs.getDeleteButton.onOpen({id},url);
  }

  statusChange=(value,id,index)=>{
    //value:当前记录状态值，true禁用，false启用
    //id:当前记录id
    //index:当前记录index值，用于改变对应state里的check值
    console.log(value,id,index)
    let status = 0;
    (value==1)?(status=0):(status=1);//改变状态值，禁用时status改为0，启用状态
    let url = '/api/users/'
    PUT(`/api/users/${id}/status`,{status})
      .then(res=>{
        if(!res){
          Feedback.toast.error('网络错误，请稍后再试！')
          return;
        }else if(res.code==200 && res.success){
          //不刷新页面，直接翻转checked值
          let items = this.state.checked;
          items[index] = !items[index];
          this.setState({checked:items})
        }else if(res.code==401 && res.msg=='请登录!'){
          Feedback.toast.error(res.msg);
          setTimeout(()=>{
            window.location.href='#/Login'
          },500)
        }else{
          Feedback.toast.error(`出错了，${res.msg}`)
          return;
      }
      },error=>{
        Feedback.toast.error(`出错了，${error}`)
        return;
      })
  };

  renderOperations = (value, index, record) => {
    return (
      <div className="operation-table-operation" style={styles.operationTable}>
        <span
          onClick={this.onOpen.bind(this,record,'edit')}
          title="编辑"
          style={styles.operBtn}
        >
          <Icon size="xs" type="edit" />
        </span>
        <span title="删除" style={styles.operBtn} onClick={this.onDelete.bind(this,record)}>
          <Icon size="xs" type="close" />
        </span>
       
      </div>
    );
  };

  renderStatus = (value, index, record) => { 
    let checked = '';
    (value==1)?(checked=true):(checked=false)
    return (
      <Switch default={false} checked={this.state.checked[index]}  onChange={this.statusChange.bind(this,value,record.id,index)}/>
    );
  };

  render() {
    const tableData = this.props.bindingData.tableData;
    return (  
      <div className="operation-table">
        <IceContainer style={styles.cardContainer}>
        <div><Button  type="primary" onClick={this.onOpen.bind(this,'','add')}>增加</Button>&emsp;
        {/* <Button  type="primary" onclick={this.changeStatus.bind(this)}>启用/禁用</Button> */}
          <EditDialog ref="getOpenDialog" onSaveChange={this.handleChildChange}/>
        </div>
          <Table
            dataSource={tableData.rows}
            isLoading={tableData.__loading}
            className="basic-table"
            style={styles.basicTable}
            hasBorder={false}
          >
            <Table.Column title="手机号" dataIndex="mobile" width={200} align="center" />
            <Table.Column title="姓名" dataIndex="loginName" width={120} align="center" />
            <Table.Column  title="性别" dataIndex="sex" width={80} align="center" />
            {/* <Table.Column  title="角色" dataIndex="roles" width={80} align="center" /> */}
            <Table.Column  title="启用/禁用" dataIndex="status" width={80} align="center" cell={this.renderStatus}  />
             <Table.Column title="操作" dataIndex="operation" width={150} align="center" cell={this.renderOperations} /> 
          </Table>
          <div style={styles.paginationContainer}>
            <Pagination
              current={tableData.page}
              pageSize={tableData.pageSize}
              total={tableData.totalCount}
              onChange={this.changePage.bind(this)}
            />
          </div>
          <ConfirmDeleteDialog  ref="getDeleteButton" onChange={this.handleChildChange}/>
        </IceContainer>
      </div>
    );
  }
}

const styles = {
  cardContainer: {
    padding: '10px 10px 20px 10px',
  },
  titleCol: {
    display: 'flex',
    flexDirection: 'row',
  },
  titleText: {
    marginLeft: '10px',
    lineHeight: '20px',
  },
  operBtn: {
    display: 'inline-block',
    width: '24px',
    height: '24px',
    borderRadius: '999px',
    color: '#929292',
    background: '#f2f2f2',
    textAlign: 'center',
    cursor: 'pointer',
    lineHeight: '24px',
    marginRight: '6px',
  },
  paginationContainer: {
    textAlign: 'right',
    paddingTop: '26px',
  },
};
